package com.dadibadi.core.security;

import com.venusoft.developer.common.security.IBaseUser;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    private String TOKEN_HEADER = "Authorization";
    @Resource
    private RedisTemplate<String, IBaseUser<String>> redisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String bearer = request.getHeader(TOKEN_HEADER);
        if (ObjectUtils.isEmpty(bearer)) {
            filterChain.doFilter(request, response);
            return;
        }
        IBaseUser<String> userDetails = redisTemplate.opsForValue().get(bearer);
        if (ObjectUtils.isEmpty(userDetails)) {
            log.warn("用户登录信息不存在");
            filterChain.doFilter(request, response);
            return;
        }

        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);
    }

}